package com.zboard.board.controller;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Locale;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zboard.board.dao.BoardListDao;

/**
 * Handles requests for the application home page.
 */
@Controller
public class BoardListController {
	
	@Autowired
	private SqlSession sqlSession;
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/board", method = RequestMethod.GET)
	public String getBoardList(Locale locale, Model model) {
		
		logger.info("[Board] List Start !!!");
		
		BoardListDao exampleDao = null;
		
		String ipAddr = null;
		
		try {
			
			exampleDao = sqlSession.getMapper(BoardListDao.class);
			
			if (getLocalServerIp() != null && getLocalServerIp().length() > 0) {
				ipAddr = getLocalServerIp();
				logger.info("[Board] ipAddr is " + ipAddr);
			}
			
			model.addAttribute("username", exampleDao.getUserName("TU_111"));
			model.addAttribute("ipAddr", ipAddr);
			
			logger.info("[Board] UserName is " + exampleDao.getUserName("TU_111"));
			
		} catch (Exception ex) {
			
		}
		
		logger.info("[Board] List End !!!");
		
		return "list";
	}
	
	/**
	 * 현재 서버의 IP 주소를 가져옵니다.
	 * 
	 * @return IP 주소
	 */
	private String getLocalServerIp()
	{
		try {
			
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				
				NetworkInterface intf = en.nextElement();
				
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					
					InetAddress inetAddress = enumIpAddr.nextElement();
					
					if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
						
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {}
		
		return null;
	}
}